# -*- coding: utf-8 -*-

'''eof
name:经济指标正向异动个数占比
code:Industry_Score_20
tableName:
columnName:
groups:行业评分模块
dependencies:INDUSTRY_INFO
type:常用指标
datasourceType:在线指标
description:
eof'''
from __future__ import division
from dateutil.relativedelta import relativedelta
from dateutil.parser import parse
import datetime
import pandas as pd


null_type_list = ['', None, 'None', 'null', 'Null', 'NULL', '/', ' ',[]]
indexType1 = ["b0203","b0103","b0303"]

def timeTypelist():
    data = INDUSTRY_INFO.get("data")
    if data in null_type_list:
        return u"缺失值"
    else:
        #计算factor1
        economyIndicatorDetail = data.get("economyIndicatorDetail")
        if economyIndicatorDetail in null_type_list:
            return u"缺失值"
        else:
            timeDict = {}
            errorTimes = 0
            for i in economyIndicatorDetail:
                try:
                    date = i.get('publishDate')
                    dateChange = parse(date).date()
                    timeDict.update({dateChange:date})
                except:
                    errorTimes += 1
            if errorTimes == len(economyIndicatorDetail):
                return u"缺失值"
            timeMax = timeDict[max(list(timeDict.keys()))]
            timeMaxChange = max(list(timeDict.keys()))
            DATA = pd.DataFrame(economyIndicatorDetail)
            DATA = DATA[DATA["publishDate"]==timeMax]
            typeList = list(set(DATA["indicatorRound"]))
            if typeList == []:
                return u"缺失值"
            if len(typeList) == 1 and typeList[0] in null_type_list:
                return u"缺失值"
            return typeList
 
        
def Industry_Score_20():
    timeAndType = timeTypelist()
    if timeAndType == u"缺失值":
        return u"缺失值"
    data = INDUSTRY_INFO.get("data")
    if data in null_type_list:
        return u"缺失值"
    else:
        economyIndicatorDetail = data.get("economyIndicatorDetail")
        if economyIndicatorDetail in null_type_list:
            return u"缺失值"
        else:
            DATA = pd.DataFrame(economyIndicatorDetail)
            DATA = DATA[DATA["indicatorRound"].isin(timeAndType)]
            if len(DATA) == 0:
                return u"缺失值"
            resultList = []
            errorTotal = 0
            for i in timeAndType:
                if i in null_type_list:
                    errorTotal += 1
                    continue
                factor1 = 0
                factor2 = 0
                #按统计周期筛选
                DATA1 = DATA[DATA["indicatorRound"]== i].reset_index(drop = True)
                #获取季度下的数据集1和数据集2
                ##获得每个时间类型下的前两大时间点
                timeList = list(set(DATA1["publishDate"]))
                temDict = {}
                error = 0
                for k in timeList:
                    try:
                        temDict.update({k:parse(k).date()})
                    except:
                        error += 1
                if error == len(timeList):
                    errorTotal += 1
                    continue
                #在指定的统计周期下，如果没有至少两个时间节点的数据，那么则无法进行比较，所以返回异常
                if len(temDict) < 2:
                    errorTotal += 1
                    continue
                time1 = sorted(temDict.items(),key = lambda x:x[1],reverse = True)[0][0]
                time2 = sorted(temDict.items(),key = lambda x:x[1],reverse = True)[1][0]
                #生成数据集1
                DATA2 = DATA1[DATA1["publishDate"]== time1]
                #生成数据集2
                DATA3 = DATA1[DATA1["publishDate"]== time2]
                
                if len(DATA2) == 0 or len(DATA3) == 0:
                    errorTotal += 1
                    continue
                #获取两个数据集都有的指标名称列表
                intersection = list(set(list(DATA2["indicatorName"])).intersection(set(list(DATA3["indicatorName"]))))
                if len(intersection) == 1 and intersection[0] in null_type_list:
                    errorTotal += 1
                    continue
                if intersection == []:
                    errorTotal += 1
                    continue
                factor2 += len(intersection)
                DATA4 = DATA2[pd.Series(DATA2["indicatorName"].isin(intersection),index = DATA2.index)].reset_index(drop=True)
                DATA5 = DATA3[pd.Series(DATA3["indicatorName"].isin(intersection),index = DATA3.index)].reset_index(drop=True)
                errorTimes = 0
                for n in intersection:
                    try:
                        dangqi = float(DATA4[DATA4["indicatorName"] == n]["currentValue"].reset_index(drop=True)[0])
                        shangqi = float(DATA5[DATA5["indicatorName"] == n]["currentValue"].reset_index(drop=True)[0])
                        indexType = DATA4[DATA4["indicatorName"] == n]["indicatorDataType"].reset_index(drop=True)[0]
                        if indexType in null_type_list:
                           errorTimes += 1
                           continue
                        if indexType in indexType1:
                            if dangqi - shangqi > 10:
                                factor1 += 1
                        else:
                            if (dangqi - shangqi)/shangqi > 0.1:
                                factor1 += 1
                    except:
                        errorTimes += 1
                if errorTimes == len(intersection):
                    errorTotal += 1
                else:
                    resultList.append(round(factor1 / factor2,4))
            if errorTotal == len(timeAndType):
                return u"缺失值"
            else:
                return max(resultList)
        
result = Industry_Score_20()